package util.nlp;

import java.util.HashSet;
import java.util.LinkedList;

import util.io.FileInput;

public class WordNetOntology implements Constants {

	/**
	 * @param args
	 */
	
	HashDictionary ontology = null;
	HashSet<String> base_types = new HashSet<String>();
	
	public static LinkedList<String>  parseRDFWordNet(String input) {

		FileInput in = new FileInput(input);

		String line = in.readString();
		
		LinkedList<String> list = new LinkedList<String>();

		while (line != null) {

			if (line.contains("<rdf:Description")) {

				int i = line.indexOf("synset");
				int j = line.indexOf("\">");

				String key = line.substring(i, j);

				line = in.readString();
				while (line != null && line.contains(":hyponymOf")) {

					i = line.indexOf("synset");
					j = line.indexOf("\"/>");

					String value = line.substring(i, j);
					list.add(key + "\t" + value);
				//	System.out.println(key + "\t" + value);
					line = in.readString();

				}

			}

			line = in.readString();

		}
		return list;

	}
	
	public void ini(String path) {

		ontology = new HashDictionary(WordNetOntology.parseRDFWordNet(path));

		for (int i = 0; i < BASE_TYPES.length; i++) {

			
			
			base_types.add(BASE_TYPES[i]);

		}
		
		

	}
	
	
	private String getBaseClass(String synset) {

		LinkedList<String> list = ontology.getEntries(synset);
	

		
		if(base_types.contains(synset))
				return synset;
		
		for (int i = 0; list != null && i < list.size(); i++) {

			String value = list.get(i);

		//	System.out.println(synset + "\t" + value);
			if (base_types.contains(value)) {

				return value;
			} else if (!ontology.containsKey(value)) {
				return null;

			}

			else {

				return getBaseClass(value);
			}

		}

		return null;

	}

	
	
	public void enhanceDBPediaWordNet(String path){
		
		
		FileInput in = new FileInput(path);

		String line = in.readString();
		
		
		while (line != null) {

			String s[]= util.parser.DBPedia.parseEntryDbpediaWordnet(line);
			
			
			String base_type = getBaseClass(s[1]);
			System.out.println(s[0] + "\t" + s[1] + "\t" + base_type);
			line = in.readString();

		}
		
	} 
	
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		String wordnet_rdf= "/home/sergio/projects/WordNet-3.0/xml/wn20full/wordnet-hyponym.rdf";
		String wordnet = "/media/sata/data/wikipedia/wordnet_links.nt";
		WordNetOntology onto=  new WordNetOntology();
		
		onto.ini(wordnet_rdf);
		
		
		onto.enhanceDBPediaWordNet(wordnet);
		//System.out.println("buscando................");
		//System.out.println(onto.getBaseClass("synset-innervation-noun-2"));
		
	}

}
